package lib

func init() {
	Probs = append(Probs, Problem{
		Num:         221,
		Discription: "最大正方形",
		Level:       2,
		Labels: map[string]int{
			"矩阵": 1,
			"动态规划": 1,
		},
	})
}

func MaximalSquare(matrix [][]byte) int {
	m := len(matrix)
	n := len(matrix[0])
	dp := make([][]int, m)
	for i := 0; i < m; i++ {
		dp[i] = make([]int, n)
	}

	max := 0
	for i := 0; i < m; i++ {
		if matrix[i][0] == '1' {
			dp[i][0] = 1
			max = 1
		}
	}
	for j := 1; j < n; j++ {
		if matrix[0][j] == '1' {
			dp[0][j] = 1
			max = 1
		}
	}

	for i := 1; i < m; i++ {
		for j := 1; j < n; j++ {
			if matrix[i][j] == '0' {
				dp[i][j] = 0
				continue
			}

			//最后记得+1
			dp[i][j] = min(min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) + 1
			if dp[i][j] > max {
				max = dp[i][j]
			}
		}
	}

	return max*max
}
